import React, { useState, useEffect, useCallback } from "react";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/components/ui/use-toast";
import {
  X,
  Save,
  Sparkles,
  FileText,
  Info,
  Loader2,
  CheckCircle,
  AlertTriangle,
  ChevronDown,
  ChevronUp,
  Lightbulb,
  AlertCircle,
  ListChecks,
} from "lucide-react";

export default function TensionSectionSchemeCreator({
  tensionSections,
  projects,
  towers,
  crossingPoints,
  methodTemplates,
  mode,
  onSuccess,
  onCancel,
  aiRecommendData,
}) {
  const [schemes, setSchemes] = useState([]);
  const [isCreating, setIsCreating] = useState(false);
  const [creationResults, setCreationResults] = useState([]);
  const [crossingTypes, setCrossingTypes] = useState([]);
  const [expandedSchemeIndex, setExpandedSchemeIndex] = useState(-1); // 控制AI推荐详情展开/折叠

  const { toast } = useToast();

  // 获取跨越类型字典数据
  const loadCrossingTypeOptions = useCallback(async () => {
    try {
      const typeResponse = await DictTypeAPI.getList();
      const crossingType = typeResponse.rows?.find(
        (item) => item.dictName === "跨越类型"
      );
      if (!crossingType) throw new Error("未找到'跨越类型'字典");

      const dataResponse = await DictDataAPI.getList({
        dictType: crossingType.dictType,
      });
      const validTypes = (dataResponse.rows || [])
        .filter((item) => item.dictValue && item.dictLabel)
        .map((item) => ({
          value: item.dictValue,
          label: item.dictLabel,
        }));
      setCrossingTypes(validTypes);
    } catch (error) {
      console.error("加载跨越类型失败:", error);
      toast({
        title: "数据加载失败",
        description: "无法加载跨越类型，请稍后重试",
        variant: "destructive",
      });
    }
  }, [toast]);

  useEffect(() => {
    loadCrossingTypeOptions();
  }, [loadCrossingTypeOptions]);

  // 初始化方案列表（结合AI推荐数据）
  useEffect(() => {
    const initialSchemes = tensionSections.map((section) => {
      const project = projects.find((p) => p.id === section.projectId);
      const sectionCrossingPoints = crossingPoints.filter((cp) =>
        section.associatedCrossingPointIds?.includes(cp.id)
      );

      // 提取AI推荐数据
      const aiData = aiRecommendData || {};
      const recommendedMethod = aiData.methodTemplate?.id || "";
      const methodName = aiData.methodTemplate?.methodName || "智能推荐方法";

      return {
        tensionSectionId: section.id,
        tensionSectionName: section.name,
        projectName: project?.name || "未知项目",
        name: `${section.name}-施工方案`,
        version: "1.0",
        constructionMethod: recommendedMethod, // 优先使用AI推荐的方法ID
        selectedCrossingPointIds: sectionCrossingPoints.map((cp) => cp.id),
        availableCrossingPoints: sectionCrossingPoints,
        description: aiData.reasoning || `基于AI分析推荐使用${methodName}`,
        // 存储AI推荐的详细信息
        aiInfo: {
          advantages: aiData.advantages || [],
          alternatives: aiData.alternativeMethods || [],
          considerations: aiData.considerations || [],
          reasoning: aiData.reasoning || "AI基于杆塔和跨越点特征生成推荐",
          methodName: methodName,
          confidence: aiData.confidence || 0, // 推荐可信度
        },
        approvalStatus: "notStarted",
      };
    });

    setSchemes(initialSchemes);
  }, [tensionSections, projects, crossingPoints, aiRecommendData]);

  // 切换AI推荐详情展开/折叠
  const toggleSchemeDetails = (index) => {
    setExpandedSchemeIndex(expandedSchemeIndex === index ? -1 : index);
  };

  const handleSchemeChange = (index, field, value) => {
    setSchemes((prev) => {
      const newSchemes = [...prev];
      newSchemes[index] = { ...newSchemes[index], [field]: value };
      return newSchemes;
    });
  };

  const handleCrossingPointToggle = (schemeIndex, cpId) => {
    setSchemes((prev) => {
      const newSchemes = [...prev];
      const current = new Set(
        newSchemes[schemeIndex].selectedCrossingPointIds || []
      );
      current.has(cpId) ? current.delete(cpId) : current.add(cpId);
      newSchemes[schemeIndex].selectedCrossingPointIds = Array.from(current);
      return newSchemes;
    });
  };

  // 手动创建方案逻辑
  const handleManualCreate = async () => {
    setIsCreating(true);
    setCreationResults([]);
    const results = [];

    for (const scheme of schemes) {
      try {
        if (!scheme.name || !scheme.constructionMethod) {
          results.push({
            tensionSectionName: scheme.tensionSectionName,
            success: false,
            error: "缺少必填信息：方案名称或施工方法",
          });
          continue;
        }

        const schemeData = {
          tensionSectionId: scheme.tensionSectionId,
          selectedCrossingPointIds: scheme.selectedCrossingPointIds,
          name: scheme.name,
          version: scheme.version,
          constructionMethod: scheme.constructionMethod,
          description: scheme.description,
          approvalStatus: "notStarted",
        };

        await ConstructionSchemeAPI.create(schemeData);
        results.push({
          tensionSectionName: scheme.tensionSectionName,
          success: true,
        });
      } catch (error) {
        console.error(`创建方案失败 (${scheme.tensionSectionName}):`, error);
        results.push({
          tensionSectionName: scheme.tensionSectionName,
          success: false,
          error: error.message || "服务器错误",
        });
      }
    }

    setCreationResults(results);
    setIsCreating(false);

    const successCount = results.filter((r) => r.success).length;
    if (successCount === results.length) {
      toast({
        title: "全部创建成功",
        description: `成功创建 ${successCount} 个施工方案`,
      });
      setTimeout(() => onSuccess(), 1500);
    } else {
      toast({
        title: "部分创建成功",
        description: `成功 ${successCount} 个，失败 ${
          results.length - successCount
        } 个`,
        variant: "default",
      });
    }
  };

  // 智能创建方案（基于AI推荐数据优化）
  const handleSmartCreate = async () => {
    setIsCreating(true);
    setCreationResults([]);
    const results = [];

    for (const scheme of schemes) {
      try {
        const aiInfo = scheme.aiInfo;
        const methodTemplate = methodTemplates.find(
          (mt) => mt.id === scheme.constructionMethod
        );

        // 构建基于AI推荐的方案数据
        const schemeData = {
          tensionSectionId: scheme.tensionSectionId,
          selectedCrossingPointIds: scheme.selectedCrossingPointIds,
          name: scheme.name,
          version: scheme.version,
          constructionMethod: scheme.constructionMethod,
          description: aiInfo.reasoning || `推荐使用${aiInfo.methodName}`,
          approvalStatus: "notStarted",
          // 新增：存储AI推荐的附加信息
          aiAdvantages: aiInfo.advantages,
          aiAlternatives: aiInfo.alternatives.map((alt) => ({
            methodName: alt.alternativeMethod?.methodName,
            reason: alt.reason,
          })),
          aiConsiderations: aiInfo.considerations,
          confidence: aiInfo.confidence,
        };

        await ConstructionSchemeAPI.create(schemeData);
        results.push({
          tensionSectionName: scheme.tensionSectionName,
          success: true,
          method: aiInfo.methodName,
          confidence: aiInfo.confidence,
        });
        onCancel();
      } catch (error) {
        console.error(
          `智能创建方案失败 (${scheme.tensionSectionName}):`,
          error
        );
        results.push({
          tensionSectionName: scheme.tensionSectionName,
          success: false,
          error: error.message || "服务器错误",
        });
      }
    }

    setCreationResults(results);
    setIsCreating(false);

    const successCount = results.filter((r) => r.success).length;
    if (successCount === results.length) {
      toast({
        title: "智能创建成功",
        description: `成功创建 ${successCount} 个施工方案`,
      });
      setTimeout(() => onSuccess(), 1500);
    } else {
      toast({
        title: "部分创建成功",
        description: `成功 ${successCount} 个，失败 ${
          results.length - successCount
        } 个`,
        variant: "default",
      });
    }
  };

  const getCrossingPointLabel = (cp) => {
    const matchedType = crossingTypes.find(
      (type) => type.value === cp.crossingType
    );
    return {
      name: cp.name,
      type: matchedType?.label || cp.crossingType || "未知类型",
      difficulty: cp.difficultyLevel,
      object: cp.crossingObject,
    };
  };

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader
        className={`border-b ${
          mode === "smart"
            ? "bg-gradient-to-r from-purple-50 to-indigo-50"
            : "bg-gradient-to-r from-blue-50 to-cyan-50"
        }`}
      >
        <CardTitle className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            {mode === "smart" ? (
              <>
                <Sparkles className="w-5 h-5 text-purple-600" />
                <span>智能创建施工方案</span>
                {aiRecommendData && (
                  <Badge className="ml-2 bg-purple-100 text-purple-800">
                    AI推荐
                  </Badge>
                )}
              </>
            ) : (
              <>
                <FileText className="w-5 h-5 text-blue-600" />
                <span>手动创建施工方案</span>
              </>
            )}
          </div>
          <Button
            variant="ghost"
            size="icon"
            onClick={onCancel}
            disabled={isCreating}
          >
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        {mode === "smart" && (
          <Alert className="mb-6 bg-purple-50 border-purple-200">
            <Sparkles className="h-4 w-4 text-purple-600" />
            <AlertDescription className="text-purple-800">
              AI已根据勘查单的跨越点特征（难度、档距等）推荐最优施工方法，
              点击方案下方的"查看推荐详情"可了解分析依据
            </AlertDescription>
          </Alert>
        )}

        {creationResults.length > 0 && (
          <Alert className="mb-6">
            <Info className="h-4 w-4" />
            <AlertDescription>
              <div className="font-medium mb-2">创建结果：</div>
              <div className="space-y-1">
                {creationResults.map((result, index) => (
                  <div key={index} className="flex items-center gap-2 text-sm">
                    {result.success ? (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="text-green-700">
                          {result.tensionSectionName} - 创建成功
                          {result.method && ` (推荐: ${result.method})`}
                          {result.confidence &&
                            ` (可信度: ${result.confidence}%)`}
                        </span>
                      </>
                    ) : (
                      <>
                        <AlertTriangle className="w-4 h-4 text-red-600" />
                        <span className="text-red-700">
                          {result.tensionSectionName} - {result.error}
                        </span>
                      </>
                    )}
                  </div>
                ))}
              </div>
            </AlertDescription>
          </Alert>
        )}

        <div className="space-y-6">
          {schemes.map((scheme, index) => (
            <Card key={index} className="border-2">
              <CardHeader className="pb-3 bg-gray-50">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="font-semibold text-lg">
                      {scheme.tensionSectionName}
                    </h3>
                    <p className="text-sm text-gray-600">
                      {scheme.projectName}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline">
                      {scheme.availableCrossingPoints.length} 个跨越点
                    </Badge>
                    {mode === "smart" && scheme.aiInfo.confidence > 0 && (
                      <Badge className="bg-green-100 text-green-800">
                        可信度 {scheme.aiInfo.confidence}%
                      </Badge>
                    )}
                  </div>
                </div>
              </CardHeader>
              <CardContent className="pt-4 space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor={`name-${index}`}>方案名称 *</Label>
                    <Input
                      id={`name-${index}`}
                      value={scheme.name}
                      onChange={(e) =>
                        handleSchemeChange(index, "name", e.target.value)
                      }
                      placeholder="输入方案名称"
                      disabled={mode === "smart"}
                    />
                  </div>

                  <div>
                    <Label htmlFor={`version-${index}`}>版本号</Label>
                    <Input
                      id={`version-${index}`}
                      value={scheme.version}
                      onChange={(e) =>
                        handleSchemeChange(index, "version", e.target.value)
                      }
                      disabled={mode === "smart"}
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor={`method-${index}`}>
                    施工方法 *
                    {mode === "smart" && (
                      <Badge className="ml-2 bg-purple-100 text-purple-800 text-xs">
                        AI推荐
                      </Badge>
                    )}
                  </Label>
                  <Select
                    value={scheme.constructionMethod}
                    onValueChange={(value) =>
                      handleSchemeChange(index, "constructionMethod", value)
                    }
                    disabled={mode === "smart" && aiRecommendData}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择施工方法" />
                    </SelectTrigger>
                    <SelectContent>
                      {methodTemplates.map((mt) => (
                        <SelectItem key={mt.id} value={mt.id}>
                          {mt.methodName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {mode === "smart" && scheme.aiInfo.methodName && (
                    <p className="text-xs text-purple-600 mt-1">
                      AI推荐：{scheme.aiInfo.methodName}
                    </p>
                  )}
                </div>

                {scheme.availableCrossingPoints.length > 0 && (
                  <div>
                    <Label className="mb-2 block">选择关联的跨越点</Label>
                    <div className="border rounded-lg p-4 max-h-48 overflow-y-auto space-y-2 bg-gray-50">
                      {scheme.availableCrossingPoints.map((cp) => {
                        const cpInfo = getCrossingPointLabel(cp);
                        return (
                          <div
                            key={cp.id}
                            className="flex items-start space-x-2 p-2 hover:bg-white rounded transition-colors"
                          >
                            <Checkbox
                              id={`cp-${index}-${cp.id}`}
                              checked={scheme.selectedCrossingPointIds?.includes(
                                cp.id
                              )}
                              onCheckedChange={() =>
                                handleCrossingPointToggle(index, cp.id)
                              }
                              className="mt-1"
                              disabled={mode === "smart"}
                            />
                            <Label
                              htmlFor={`cp-${index}-${cp.id}`}
                              className="flex-1 cursor-pointer"
                            >
                              <div className="flex items-center gap-2 flex-wrap">
                                <span className="font-medium">
                                  {cpInfo.name}
                                </span>
                                <Badge variant="outline" className="text-xs">
                                  {cpInfo.type}
                                </Badge>
                                {cpInfo.object && (
                                  <Badge
                                    variant="secondary"
                                    className="text-xs"
                                  >
                                    {cpInfo.object}
                                  </Badge>
                                )}
                                {(cp.difficultyLevel === "high" ||
                                  cp.difficultyLevel === "critical") && (
                                  <Badge className="bg-red-100 text-red-800 text-xs">
                                    {cp.difficultyLevel === "critical"
                                      ? "极高难度"
                                      : "高难度"}
                                  </Badge>
                                )}
                              </div>
                            </Label>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                <div>
                  <Label htmlFor={`description-${index}`}>方案描述</Label>
                  <Textarea
                    id={`description-${index}`}
                    value={scheme.description}
                    onChange={(e) =>
                      handleSchemeChange(index, "description", e.target.value)
                    }
                    rows={2}
                    placeholder="输入方案描述..."
                    disabled={mode === "smart" && aiRecommendData?.reasoning}
                  />
                </div>

                {/* AI推荐详情（仅智能模式显示） */}
                {mode === "smart" && aiRecommendData && (
                  <>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => toggleSchemeDetails(index)}
                      className="w-full justify-between text-purple-600 hover:text-purple-800 hover:bg-purple-50"
                    >
                      <span className="flex items-center gap-1">
                        <Info className="w-4 h-4" />
                        查看AI推荐详情
                      </span>
                      {expandedSchemeIndex === index ? (
                        <ChevronUp className="w-4 h-4" />
                      ) : (
                        <ChevronDown className="w-4 h-4" />
                      )}
                    </Button>

                    {expandedSchemeIndex === index && (
                      <div className="mt-3 p-4 bg-purple-50 rounded-lg border border-purple-100 space-y-4">
                        {/* 推荐理由 */}
                        <div>
                          <h4 className="flex items-center gap-1 text-sm font-semibold text-purple-800 mb-2">
                            <Lightbulb className="w-4 h-4" />
                            推荐理由
                          </h4>
                          <p className="text-sm text-gray-700 pl-5">
                            {scheme.aiInfo.reasoning ||
                              "基于杆塔和跨越点特征分析"}
                          </p>
                        </div>

                        {/* 方案优势 */}
                        {scheme.aiInfo.advantages.length > 0 && (
                          <div>
                            <h4 className="flex items-center gap-1 text-sm font-semibold text-purple-800 mb-2">
                              <ListChecks className="w-4 h-4" />
                              方案优势
                            </h4>
                            <ul className="text-sm text-gray-700 pl-5 space-y-1 list-disc">
                              {scheme.aiInfo.advantages.map((adv, i) => (
                                <li key={i}>{adv}</li>
                              ))}
                            </ul>
                          </div>
                        )}

                        {/* 替代方案 */}
                        {scheme.aiInfo.alternatives.length > 0 && (
                          <div>
                            <h4 className="flex items-center gap-1 text-sm font-semibold text-purple-800 mb-2">
                              <AlertCircle className="w-4 h-4" />
                              替代方案
                            </h4>
                            <div className="text-sm text-gray-700 pl-5 space-y-2">
                              {scheme.aiInfo.alternatives.map((alt, i) => (
                                <div
                                  key={i}
                                  className="p-2 bg-white rounded border border-gray-100"
                                >
                                  <p className="font-medium">
                                    {alt.alternativeMethod?.methodName ||
                                      `替代方案${i + 1}`}
                                  </p>
                                  <p className="text-xs mt-1">{alt.reason}</p>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* 注意事项 */}
                        {scheme.aiInfo.considerations.length > 0 && (
                          <div>
                            <h4 className="flex items-center gap-1 text-sm font-semibold text-purple-800 mb-2">
                              <AlertTriangle className="w-4 h-4" />
                              施工注意事项
                            </h4>
                            <ul className="text-sm text-gray-700 pl-5 space-y-1 list-disc">
                              {scheme.aiInfo.considerations.map((item, i) => (
                                <li key={i}>{item}</li>
                              ))}
                            </ul>
                          </div>
                        )}
                      </div>
                    )}
                  </>
                )}
              </CardContent>
            </Card>
          ))}
        </div>

        <div className="flex justify-end gap-3 pt-6 mt-6 border-t">
          <Button variant="outline" onClick={onCancel} disabled={isCreating}>
            取消
          </Button>
          <Button
            onClick={mode === "smart" ? handleSmartCreate : handleManualCreate}
            disabled={isCreating}
            className={
              mode === "smart"
                ? "bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700"
                : "bg-blue-600 hover:bg-blue-700"
            }
          >
            {isCreating ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                创建中...
              </>
            ) : (
              <>
                {mode === "smart" ? (
                  <>
                    <Sparkles className="w-4 h-4 mr-2" />
                    智能创建方案
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4 mr-2" />
                    创建方案
                  </>
                )}
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
